/*
 * Copyright (c) 2020 hebeiyiliuba.com
 * All rights reserved.
 *
 */
package org.jeecg.modules.third.sendsms.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.third.sendsms.dto.RequestlistsDTO;
import org.jeecg.modules.third.sendsms.util.HttpUtil;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发送短信消息
 * https://www.huaweiita.com/itaportal/pc/site/customerService/sms-product/
 * @author duanlikao
 * @created 2020/11/30
 */
@Slf4j
@Service
public class SendSmsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendSmsService.class);

    @Value(value="${sms.domain}")
    private String  SMS_DOMAIN ;
    @Value(value="${sms.aliyun.active:0}")
    private String aliyunActive;

    @Resource
    private BaseCommonService baseCommonService;
    @Resource AliyunSmsService aliyunSmsService;

    private  boolean doSendSms(String  smsContent ,Map<String, Object> bady) throws Exception {
        String url = SMS_DOMAIN;
        try {
//            LOGGER.info("SendSmsService | doSendSms | url :{} | sendSmsDTO:{}  ",url,bady );
            String result = HttpUtil.doPostSms(url, bady);
            JSONObject resObject = JSONObject.parseObject(result);
            log.info("发送SMS短信，{} -> {} " , smsContent, JSONObject.toJSONString(resObject));
            int resul = CommonConstant.OPERATE_TYPE_8;
            if (resObject != null &&  "0".equals(resObject.get("resultCode"))) {
                resul = CommonConstant.OPERATE_TYPE_7;
            }
            //添加日志 "+JSONObject.toJSONString(bady) +" result :
            baseCommonService.addLog(smsContent, CommonConstant.LOG_TYPE_3, resul);
            return resul == 7 ? true : false;

        } catch (Exception e) {
            LOGGER.info("SendSmsService|Exception|{}", e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     *
     * @param mobile
     * @param smsTemplateId
     * @param paramValues
     * @param accout
     * @param passward
     * @return
     */
    private  Map<String, Object> buildRequestBody(String mobile, String smsTemplateId,
                                                       Map<String, String> paramValues,
                                                       String accout, String passward) {
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null || !systemConfig.getSmsIzUse()){
            throw new JeecgBootException("平台短信服务暂未开启,请联系管理员。");
        }

        if (null == mobile || null == smsTemplateId || null == accout || null == passward) {
            LOGGER.info("SendSmsService buildRequestBody(): mobiles, templateId or templateParas or account o" +
                    "r password is null.");
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        List<RequestlistsDTO> requestLists = new ArrayList<RequestlistsDTO>();
        RequestlistsDTO mtSmsMessage = new RequestlistsDTO();
        List<String> mobiles = new ArrayList<String>();
        mobiles.add(mobile);
        mtSmsMessage.setMobiles(mobiles);
        mtSmsMessage.setTemplateId(smsTemplateId);
        mtSmsMessage.setTemplateParas(paramValues);
        mtSmsMessage.setSignature(systemConfig.getSmsSignature());
        requestLists.add(mtSmsMessage);
        map.put("account", accout);
        map.put("password", passward);
        map.put("requestLists", requestLists);
        return map;
    }

    /**
     *
     * @param mobile
     * @param templateParas
     * @return
     * @throws Exception
     */
    public  boolean sendSms(String  mobile ,Map<String, String> templateParas) throws Exception {
        HyConfig systemConfig = HyConfigUtils.getConfig();
        if(systemConfig == null && !systemConfig.getSmsIzUse()&&!systemConfig.getAliyunSmsIsUse()){
            throw new JeecgBootException("平台短信服务暂未开启,请联系管理员。");
        }

        /*if("1".equals(aliyunActive)){
            log.info("阿里云发送短信");
            return aliyunSmsService.sendSms(mobile, templateParas);
        } else {*/
        if (systemConfig.getAliyunSmsIsUse()!=null&&systemConfig.getAliyunSmsIsUse()) {
            String accessKeyId = systemConfig.getAccessKeyId();
            String accessKeySecret = systemConfig.getAccessKeySecret();
            String templateCode = systemConfig.getTemplateCode();
            String signName = systemConfig.getSignName();
            log.info("阿里云发送短信");
            String smsContent = mobile +" 您的平台验证码:"+templateParas.get("code")+",有效期"+templateParas.get("number")+"分钟，请勿泄露。"+systemConfig.getSignName();
            log.info("发送SMS短信，{} -> {} " , smsContent);
            return aliyunSmsService.sendSms(mobile, templateParas,accessKeyId,accessKeySecret,templateCode,signName);
        }else {

            //String mobile = "13718966844";
            String smsTemplateId =  systemConfig.getSmsTemplateId();
            String account = systemConfig.getSmsAccount();
            String passward = systemConfig.getSmsPassword();
//        Map<String, String> templateParas = new HashMap<String, String>();
//        templateParas.put("code", "456546");
//        templateParas.put("number", "10");

            Map<String, Object> body = buildRequestBody(mobile, smsTemplateId, templateParas, account, passward);
            if (null == body || body.isEmpty()) {
                LOGGER.info("SendSmsService sendSms body is null.");
                return false;
            }
            String smsContent = mobile +" 您的平台验证码:"+templateParas.get("code")+",有效期"+templateParas.get("number")+"分钟，请勿泄露。"+systemConfig.getSmsSignature();
            return doSendSms(smsContent ,body);
        }
    }


}
